package org.bookie.model.services.impl;

import org.apache.commons.logging.Log;
import org.bookie.model.Role;
import org.bookie.model.User;
import org.bookie.model.services.UserDAO;
import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate implementation of the {@link UserDAO}
 * 
 * @author zubairov
 */
public class HibernateUserDAO extends GenericHibernateDAO<User, Long> implements
		UserDAO {

	private Log log;
	
	/**
	 * {@inheritDoc}
	 */
	public User findByEmail(String email) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		return (User) crit.add(Restrictions.eq("email", email)).uniqueResult();
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean activate(String key) {
		log.debug("Processing activation " + key);
		Transaction tx = null;
		try {
			tx = getSession().beginTransaction();
			User user = (User) getSession()
					.createCriteria(User.class).add(
							Restrictions.eq("activationKey", key)).uniqueResult();
			if (null == user) {
				log.debug("No activation record with key " + key + " was found");
				return false;
			}
			log.debug("Activation key was found, activating user " + user);
			if (user.getRole().equals(Role.GUEST)) {
				log.debug("Changing the user role to USER");
				user.setRole(Role.USER);
			}
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		}
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	public User findByUserName(String userName) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		return (User) crit.add(Restrictions.eq("username", userName)).uniqueResult();
	}	
	
	/**
	 * {@inheritDoc}
	 */
	public void refresh(User user) {
		getSession().refresh(user);
	}
	
	/**
	 * @category injector
	 * @param log
	 */
	public void setLog(Log log) {
		this.log = log;
	}

}
